package cn.cdeden.knowledge.controller.team;


import cn.cdeden.common.core.domain.R;
import cn.cdeden.common.core.utils.MapstructUtils;
import cn.cdeden.common.satoken.utils.LoginHelper;
import cn.cdeden.knowledge.domain.LatelyUserTeam;
import cn.cdeden.knowledge.domain.SysMessage;
import cn.cdeden.knowledge.domain.Team;
import cn.cdeden.knowledge.domain.dto.TeamDto;
import cn.cdeden.knowledge.domain.dto.TeamFilesTreeDto;
import cn.cdeden.knowledge.domain.dto.TeamQueryParam;
import cn.cdeden.knowledge.domain.vo.TeamLatelyUseVo;
import cn.cdeden.knowledge.enums.ResultEnum;
import cn.cdeden.knowledge.enums.TeamParamEnum;
import cn.cdeden.knowledge.enums.TeamTypeEnum;
import cn.cdeden.knowledge.service.*;
import cn.cdeden.system.api.model.LoginUser;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Chen
 * @date 2022-09-05
 **/

@Controller
@Slf4j
//@Api(tags = "团队文档管理")
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/team")
public class TeamController {

    private final TeamService teamService;

    private final TeamFilesTreeService teamFilesTreeService;

    private final TeamMemberService teamMemberService;

    private final LatelyUserTeamService latelyUserTeamService;

    private final SysMessageService sysMessageService;


//    @Log("查询团队文档")
//    @ApiOperation("查询团队文档")
    @GetMapping(value = "/query")
    @ResponseBody
    public R query(TeamQueryParam query, Pageable pageable) {
        return R.ok(teamService.queryByPerm(query,pageable));
    }

//    @Log("查询删除的团队")
//    @ApiOperation("查询删除的团队")
    @GetMapping(value = "/queryByDelete")
    @ResponseBody
    public R queryByDelete(TeamQueryParam query,Pageable pageable) {
        return R.ok(teamService.queryByDelete(query,pageable));
    }

//    @Log("查询团队类型")
//    @ApiOperation("查询团队类型")
    @GetMapping(value = "/getTypeById")
    @ResponseBody
    public R getTypeById(@Param("id") Long id) {
        return R.ok(teamService.getById(id).getType());
    }

//    @Log("恢复团队")
//    @ApiOperation("恢复团队")
    @GetMapping(value = "/recoverTeam")
    @ResponseBody
    public R recoverTeam(Integer teamId) {
        return R.ok(teamService.recoverTeam(teamId));
    }

//    @Log("查询团队详细信息")
//    @ApiOperation("查询团队详细信息")
    @GetMapping(value = "/getInformation")
    @ResponseBody
    public R getInformation(Integer id) {
        return R.ok(teamService.getInformation(id));
    }

//    @Log("设置团队添加成员的默认角色")
//    @ApiOperation("设置团队添加成员的默认角色")
    @PostMapping(value = "/setDefaultRole")
    @ResponseBody
    public R setDefaultRole(@RequestBody TeamDto resources) {
        return R.ok(teamService.updateById(resources));
    }

//    @Log("新增团队文档")
//    @ApiOperation("新增团队文档")
    @PostMapping(value = "/add")
//    @PreAuthorize("@el.check('team:add')")
    public R create(@RequestBody TeamDto resources) {
        resources.setType(TeamTypeEnum.NORMAL_TEAM.getNum());//设置普通团队
        return R.ok(teamService.insert(resources,true));
    }

//    @Log("修改团队基本信息")
//    @ApiOperation("修改团队基本信息")
    @PostMapping(value = "/update")
    public R update(@RequestBody TeamDto resources) {
        Team team = teamService.getById(resources.getId());
        if (!team.getOwner().equals(String.valueOf(LoginHelper.getLoginUser().getUserId()))){
            throw new RuntimeException("无操作权限！");
        }
        int i = teamService.updateById(resources);
        //修改团队树名字
        TeamFilesTreeDto teamFilesTreeDto = new TeamFilesTreeDto();
        teamFilesTreeDto.setId(Long.valueOf(team.getHeadNodeId()));
        teamFilesTreeDto.setRealName(resources.getTeamName());
        teamFilesTreeService.rename(teamFilesTreeDto);

        return R.ok(i);
    }

//    @Log("查询所有团队文档")
//    @ApiOperation("查询所有团队文档")
    @GetMapping(value = "/queryAll")
    @ResponseBody
    public R queryAll(TeamQueryParam query,Pageable pageable) {
        return R.ok(teamService.queryAll(query,pageable));
    }

//    @Log("修改团队所有者")
//    @ApiOperation("修改团队所有者")
    @PostMapping(value = "/updateOwner")
//    @PreAuthorize("@el.check('teamConfig:edit')")
    public R updateOwner(@RequestBody TeamDto resources) {
        //用于后台管理员转交团队
        int i = teamService.ownerHandOver(resources);
        return R.ok(i);
    }

//    @Log("所有者移交团队")
//    @ApiOperation("所有者移交团队")
    @PostMapping(value = "/ownerHandOver")
    public R ownerHandOver(@RequestBody TeamDto resources) {

        Team team = teamService.getById(resources.getId());
        //所有者转交团队 判断权限
        if (!team.getOwner().equals(String.valueOf(LoginHelper.getLoginUser().getUserId()))){
            return R.fail(ResultEnum.PERM_ERROR.getNum(),"无权更换团队管理员");
        }
        int i = teamService.ownerHandOver(resources);
        return R.ok(i);
    }


//    @Log("删除团队文档")
//    @ApiOperation("删除团队文档")
    @GetMapping(value = "/delete")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "ids", value = "删除ID数组", dataType = "List", required = false),
//    })
    @Transactional
    public R delete(@RequestParam List<Integer> ids) {
        for (Integer integer : ids) {
            R delete = deleteById(integer);
            if (delete !=null){
                return delete;
            }
        }
        return R.ok("200");
    }
    @Transactional
    public R deleteById(Integer id) {
        Team team = teamService.getById(id);
        if (team.getType().equals(TeamTypeEnum.PROJECT_TEAM.getNum())){
            return R.fail("项目团队：“" + team.getTeamName() +"“ 不可删除");
        }
        LoginUser user = LoginHelper.getLoginUser();
        if (team.getOwner().equals(user.getUserId().toString())) {
            team.setDeleteId(String.valueOf(user.getUserId()));
            team.setDeleteBy(String.valueOf(user.getUsername()));
            team.setDeleteTime(new Date());
            teamService.updateById(team);
        } else {
            return R.fail("无团队 “" + team.getTeamName() +"“ 的删除权限！");
        }
        return null;
    }

//    @Log("创建模板文档")
//    @ApiOperation("创建模板文档")
    @GetMapping(value = "/createTemplateFile")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "templateId", value = "模板id", dataType = "Long", required = true),
//            @ApiImplicitParam(name = "parentFolderId", value = "树id", dataType = "Long", required = true),
//            @ApiImplicitParam(name = "fileName", value = "文件名称", dataType = "String", required = true),
//            @ApiImplicitParam(name = "type", value = "模板文件类型", dataType = "String", required = false)
//    })
    public R<TeamFilesTreeDto> createTemplateFile(Long templateId, Long parentFolderId, String fileName,String type){
        TeamFilesTreeDto fileFromTemplate = teamFilesTreeService.createFileFromTemplate(templateId, parentFolderId, fileName, type,"team");
        return R.ok(fileFromTemplate);
    }

//    @GetMapping("/count-team-project")
////    @Log("统计团队项目的数据")
////    @ApiOperation("统计团队项目的数据")
//    public R<TeamCountDto> countTeamProject(ProjectQueryParam param, Pageable pageable) {
//        FileUserDto user = FileUserUtils.getUser();
//        List<TeamCountDto> teamCountDtoList = new ArrayList<>();
//        TeamQueryParam query = new TeamQueryParam();
//        PageInfo<TeamDto> teamDtoPageInfo = teamService.queryByPerm(query, pageable);
//        TeamCountDto teamCountDto = new TeamCountDto();
//        teamCountDto.setName("团队");
//        teamCountDto.setNumber(teamDtoPageInfo.getTotalElements());
//        teamCountDtoList.add(teamCountDto);
//        //
//        List<ProjtDto> projtDtos = countFrmProjectService.queryMyProject(param, String.valueOf(user.getId()));
//        TeamCountDto projectCountDto = new TeamCountDto();
//        projectCountDto.setName("项目");
//        projectCountDto.setNumber((long)projtDtos.size());
//        teamCountDtoList.add(projectCountDto);
//        return R.ok()(teamCountDtoList);
//    }

    @PostMapping("/add-lately-team")
//    @ApiOperation("增加最近使用团队的数据")
//    @Log("增加最近使用团队的数据")
    public R addlatelyTeam(@RequestBody LatelyUserTeam latelyUserTeam) {
        LoginUser user = LoginHelper.getLoginUser();
        latelyUserTeam.setUserId(user.getUserId());
        latelyUserTeamService.addlatelyTeam(latelyUserTeam);
        return R.ok();
    }

    @GetMapping("/get-lately-team")
//    @Log("查询最近使用的团队的信息")
//    @ApiOperation("查询最近使用的团队的信息")
    public R<List<TeamLatelyUseVo>> getLatelyTeam() {
        LoginUser user = LoginHelper.getLoginUser();
        List<LatelyUserTeam> latelyUserTeamList = latelyUserTeamService.list(new QueryWrapper<LatelyUserTeam>().eq("user_id", user.getUserId()));
        //判断是否有查看的权限
        List<Long> removeTeamIds = new ArrayList<>();
        latelyUserTeamList.forEach(v -> {
            try {
                Boolean aBoolean = teamMemberService.checkPermission(Long.toString(v.getTeamId()), user, TeamParamEnum.CHECK.getParam());
            } catch (Exception e) {
                removeTeamIds.add(v.getTeamId());
            }
        });
        List<Long> teamIds = latelyUserTeamList.stream().map(LatelyUserTeam::getTeamId).collect(Collectors.toList());
        teamIds.removeAll(removeTeamIds);
        List<TeamLatelyUseVo> teamLatelyUseVos = new ArrayList<>();
        if (!teamIds.isEmpty()) {
            List<Team> teamList = teamService.list(new QueryWrapper<Team>().in("id", teamIds));
            teamLatelyUseVos = MapstructUtils.convert(teamList, TeamLatelyUseVo.class);
            teamLatelyUseVos.forEach(v -> {
                Long space = v.getSpace();
                Long usedSpace = v.getUsedSpace();
                if (usedSpace != 0l && usedSpace > 0) {
                    v.setUseOfSpace(Math.round(((double) usedSpace / space) * 100));
                } else {
                    v.setUseOfSpace(0l);
                }

            });
        }
        return R.ok(teamLatelyUseVos);
    }

    @GetMapping("/get-team-message")
//    @Log("查询对应团队最近的团队信息")
//    @ApiOperation("查询对应团队最近的团队信息")
    public R getTeamMessage(Integer teamId) {
        List<SysMessage> sysMessageList = sysMessageService.list(new QueryWrapper<SysMessage>()
                .eq("message_type", "file")
                .eq("file_type", "team")
                .eq("type", "file")
                .eq("team_id", teamId));
        return R.ok(sysMessageList);
    }

}
